package notesDetection;

import java.applet.Applet;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

public class notesDetectionApplet extends Applet {

	/**
	 * This class should work as a support for HTML GUI.
	 * BUT: In order to access files through Applet - the applet must be signed.
	 * That's a headache... so this JApplet is left this way...
	 * 
	 * ##########################################################
	 * THE JAVA APPLET IS NOT FUNCTIONAL AND WAS LEFT AS A BACKUP
	 * ##########################################################
	 */
	
	/**
	 * Auto-generated UID
	 */
	private static final long serialVersionUID = 9861962487887420L;
	
	private String _inputFilePath; 
	private String _outputFilePath;
	
	private String _lastError;
	
	public enum AppErrorCodes
	{
		ERROR_OK (0),
		ERROR_INPUT_FILE_DO_NOT_EXIST (10),
		ERROR_GENERAL(100);
		
		private int _errorCode;
		
		AppErrorCodes(int errorCode)
		{
			_errorCode = errorCode;
		}
		
		public int GetValue()
		{
			return _errorCode;
		}
	}
	
	public notesDetectionApplet()
	{
		_inputFilePath = "";
		_outputFilePath = "";
		_lastError = "";
	}
	
	public void setInputFilename(String inputFilePath)
	{
		_inputFilePath = inputFilePath;
	}
	
	public void setOutputFilename(String outputFilePath)
	{
		_outputFilePath = outputFilePath;
	}
	
	public int Run()
	{
	    InputStream inpStream = GetInputStream(_inputFilePath); 
		if(inpStream == null)
		{
			return AppErrorCodes.ERROR_INPUT_FILE_DO_NOT_EXIST.GetValue();
			
		}
		OutputStream outStream = GetOutputStream(_outputFilePath);
		if(outStream == null)
		{
			return AppErrorCodes.ERROR_GENERAL.GetValue();
		}
		return AppErrorCodes.ERROR_OK.GetValue();
		
	}
	
	public String getLastError()
	{
		return _lastError;
	}
	
	private InputStream GetInputStream(String filePath)
	{
		URL source;
		InputStream inpStream;
		_lastError = "OK";
		
		try
		{
			if(filePath.startsWith("file:"))
			{
				source = new URL(filePath);
			}
			else
			{
				source = new URL(getCodeBase(), filePath);
			}
			inpStream = source.openStream();
		
		} catch (Exception e) {
			_lastError = "Unable to open file: " + _inputFilePath + ": open URL.\n" + e.getMessage();
			return null;
		}
		
		
		return inpStream;
	}
	
	private OutputStream GetOutputStream(String filePath)
	{
		//URL source;
		FileOutputStream outStream;
		
		try
		{
			if(filePath.startsWith("file:"))
			{
				//source = new URL(filePath);
			}
			else
			{
				//source = new URL(getCodeBase(), filePath);
			}
			
			outStream = new FileOutputStream(filePath);
		} catch (Exception e) {
			return null;
		}
		return outStream;
	}
}
